from django.contrib import admin
from django.utils.translation import gettext_lazy
from django.contrib.admin import helpers

from utils.model import NoDeleteSelectModelAdmin, BaseModelAdmin
from apps.app_auth_provider.models import (
    AuthConfig,
    InternalUser,
    ExternalUser,
    AuthProvider,
    AuthCode,
    EmailVerificationCode,
    AuthRecord,
    AllowedRedirect
)
from apps.app_auth_provider.forms import AuthConfigForm
from apps.app_auth_provider.managers import auth_provider_configs


@admin.register(AuthConfig)
class AuthConfigAdmin(NoDeleteSelectModelAdmin):
    form = AuthConfigForm
    list_display = ('id', 'name', 'value', 'remark', 'created_at', 'updated_at')
    list_display_links = ['id', 'name']
    actions = ('update_configs',)
    show_full_result_count = False

    @admin.action(description=gettext_lazy('清理更新配置项'))
    def update_configs(self, request, queryset):
        auth_provider_configs.get_configs_no_cache(remove_invalid=True)

    update_configs.act_not_need_selected = True

    def changelist_view(self, request, extra_context=None):
        if request.method == "POST":
            action = self.get_actions(request)[request.POST['action']][0]
            act_not_need_selected = getattr(action, 'act_not_need_selected', False)
            if act_not_need_selected:
                post = request.POST.copy()
                post.setlist(helpers.ACTION_CHECKBOX_NAME, [0])
                request.POST = post

        return super().changelist_view(request, extra_context)

    def get_changelist_instance(self, request):
        cl = super().get_changelist_instance(request)
        cl.show_admin_actions = True
        return cl

    def save_model(self, request, obj, form, change):
        super().save_model(request=request, obj=obj, form=form, change=change)
        auth_provider_configs.clear_cache()


@admin.register(InternalUser)
class InternalUserAdmin(NoDeleteSelectModelAdmin):
    list_display = ('id', 'email', 'true_name', 'is_active', 'org_name', 'created_at', 'description')
    list_display_links = ('id',)
    list_filter = ('is_active',)
    search_fields = ('email', 'true_name')
    show_full_result_count = False


@admin.register(ExternalUser)
class ExternalUserAdmin(NoDeleteSelectModelAdmin):
    list_display = (
        'id', 'provider_type', 'external_id', 'internal_user', 'email', 'true_name', 'org_name', 'created_at'
    )
    list_display_links = ('id',)
    list_filter = ('provider_type',)
    list_select_related = ('internal_user',)
    search_fields = ('email', 'true_name', 'external_id')
    raw_id_fields = ('internal_user',)
    show_full_result_count = False


@admin.register(AuthProvider)
class AuthProviderAdmin(NoDeleteSelectModelAdmin):
    list_display = (
        'id', 'name', 'provider_type', 'is_active', 'endpoint_url', 'meta_url', 'callback_url',
        'client_id', 'client_secret'
    )
    list_display_links = ('id',)


@admin.register(AuthCode)
class AuthCodeAdmin(BaseModelAdmin):
    list_display = ('id', 'internal_user', 'used', 'expired_at', 'created_at')
    list_display_links = ('id',)
    list_filter = ('used',)
    raw_id_fields = ('internal_user',)
    search_fields = ('internal_user__email', 'id')


@admin.register(EmailVerificationCode)
class EmailVerificationCodeAdmin(BaseModelAdmin):
    list_display = ('id', 'email', 'code', 'external_user', 'expired_at', 'created_at')
    list_display_links = ('id',)
    list_select_related = ('external_user',)
    raw_id_fields = ('external_user',)
    search_fields = ('email', 'code')


@admin.register(AllowedRedirect)
class AllowedRedirectAdmin(BaseModelAdmin):
    list_display = ('id', 'name', 'pattern', 'pattern_type', 'is_active', 'created_at', 'create_user', 'description')
    list_display_links = ('id',)
    list_filter = ('is_active',)
    search_fields = ('name', 'pattern')


@admin.register(AuthRecord)
class AuthRecordAdmin(BaseModelAdmin):
    list_display = (
        'id', 'provider_type', 'auth_status', 'remote_ip', 'hostname', 'redirect_uri', 'email', 'created_at'
    )
    list_display_links = ('id',)
    list_filter = ('provider_type', 'auth_status')
    raw_id_fields = ('internal_user',)
    search_fields = ('remote_ip', 'hostname', 'email')
